from machine import Pin, time_pulse_us
import time

class SonicSensor(object):
    def __init__(self, triggerPin, echoPin, echo_timeout_us=500*2*30):
        self.echo_timeout = echo_timeout_us
        self.trigger = Pin(triggerPin, Pin.OUT)
        self.echo = Pin(echoPin, Pin.IN)
        self.trigger.value(0)
        
    def getPulseTime(self):
        self.trigger.value(0)
        time.sleep_us(5)
        
        #send 1 microsecond pulse
        self.trigger.value(1)
        time.sleep_us(10)
        self.trigger.value(0)
        
        try:
            #record pulse duration, on echo, when value is one, time out in echo_timeout
            pulseTime = time_pulse_us(self.echo, 1, self.echo_timeout)
            return pulseTime
        except OSError:
            # if 110 time out
            if OSError.args[0] == 110:
                raise OSError('out of range')
            raise OSError
        
    def scan_cm(self):
        #get pulse time
        #distance in cm
        distance_cm = (getPulseTime() / 2) / 29.1
        #return result string
        return distance_cm

